package com.tt.lcd.qunyangGPRS.aSDK;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.beidouapp.et.ConnectOptions;
import com.beidouapp.et.ErrorInfo;
import com.beidouapp.et.IActionListener;
import com.beidouapp.et.IFriendsActionListener;
import com.beidouapp.et.ISDKContext;
import com.beidouapp.et.ISDKContextCallback;
import com.beidouapp.et.Message;
import com.beidouapp.et.MessageType;
import com.beidouapp.et.SDKContextManager;
import com.beidouapp.et.SDKContextParameters;
import com.beidouapp.et.Server;
import com.beidouapp.et.client.domain.DocumentInfo;
import com.beidouapp.et.client.domain.UserInfo;
import com.tt.lcd.qunyangGPRS.dao.MyUser;
import com.tt.lcd.qunyangGPRS.dao.renshen.XiaoqunyangDao;
import com.tt.lcd.qunyangGPRS.entity.XiaoQunYnag;
import com.tt.lcd.qunyangGPRS.utils.MyApplication;
import com.tt.lcd.qunyangGPRS.utils.Register;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SDKserver extends Service {
	Server server; // 通讯服务
	ISDKContext sdkContext;

	public Map<String, ArrayList<byte[]>> uID = new HashMap<String, ArrayList<byte[]>>();

	public boolean connect = false;
	private XiaoqunyangDao x;

	public class LocalBinder extends Binder {
		public SDKserver getServeice() {
			return SDKserver.this;
		}
	}

	private LocalBinder mLocBin = new LocalBinder();

	@Override
	public IBinder onBind(Intent intent) {
		Log.e("server", "onBind");
		return mLocBin;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.e("server", "onCreate");

		x = new XiaoqunyangDao(this);
		x.create();

		ArrayList<XiaoQunYnag> list = new ArrayList<XiaoQunYnag>();
		list = x.selectAll();

		for (int i = 0; i < list.size(); i++) {
			this.uID.put(list.get(i).getUid() + "&TX", new ArrayList<byte[]>());

		}
		if (!new MyUser(this).selectUID().equals("")) {
			init();
			this.scanServer();
		}
	}

	public void init() {
		SDKContextParameters sdkCP = new SDKContextParameters();
		sdkCP.setUid(new MyUser(this).selectUID());
		sdkCP.setAppKey("33d8bcea-ae05-711133");
		sdkCP.setSecretKey("9ffcbc99885fb9c36c7d8512f5846488");
		sdkCP.setBlanceServerAddress("lb.kaifakuai.com");// 负载服务器地址
		// sdkCP.setLocalIp(); //手机的ip，只使用外网不用填
		sdkCP.setBlanceServerPort(8085);
		sdkContext = SDKContextManager.createContext(sdkCP);
		sdkContext.setCallback(new ISDKContextCallback() {

			@Override
			public void onServer(Server arg0) {
				// 返回服务器
				server = arg0;
				connectServer();
				Log.e("tets", "返回服务器");
			}

			@Override
			public void onPeerState(String UID, String stateCode) {
				// 用户状态变化 ///已广播的形式发个主Activity
				// Intent it = new Intent("lcd.gprs.user.State");
				// it.putExtra("cmd","state");
				// sendBroadcast(it);
			}

			@Override
			public void onMessage(MessageType arg0, String zhuti, Message arg2) {
				byte[] b = arg2.getPayload();
				String r = "";
				for (int i = 0; i < b.length; i++) {
					int c = b[i] & 127;
					if (b[i] < 0) {
						c = c + 128;
					}
					r = r + Integer.toString(c, 16) + " ";
				}
				Log.e("sdk", "主题" + zhuti + ":"+r);
				if (b[0] == 0x64 && b[1] == 0x61 && b[2] == 0x74
						&& b[3] == 0x61) {// 判断是不是数据
					Log.e("asdf", "数据");
					if (b[20] == 1) { // 判断是不是第一包
						uID.get(zhuti).clear();
						Log.e("asdf", "第一包，清楚旧缓存");
					}
					uID.get(zhuti).add(b);

					if (b[19] == uID.get(zhuti).size()
							|| (b[19] == 0 && b[20] == 1)) {// 如果包总数等于集合大小则认为已收完
						byte[] data = new byte[10240];
						Log.e("asdf", "最后一包");
						int c = 0;
						for (int i = 0; i < uID.get(zhuti).size(); i++) { // 取出并合并数据
							byte[] bi = uID.get(zhuti).get(i);

							if (i == 0) {// 第一包数据记录序列号等信息
								for (int j = 0; j < 15; j++) {
									data[j] = bi[j + 4];
									int c1 = bi[j + 4] & 127;
									if (bi[j + 4] < 0) {
										c1 = c1 + 128;
									}
								}
								data[15] = bi[21];
								data[16] = bi[22];
								data[17] = bi[23];
								c = 18;
							}

							for (int j = 24; j < bi.length; j++) {
								data[c] = bi[j];
								c++;
							}
						}
						// 计算出有效数据长度，排除空数据
						int d = data[14] & 127;
						if (data[14] < 0) {
							d = d + 128;
						}

						int g = data[13] & 127;
						if (data[13] < 0) {
							g = g + 128;
						}

						int z = (g << 8) + d;// 数据总条数

						z = z * 24 + 18;// 有效字节总数

						byte[] y = new byte[z];
						for (int i = 0; i < y.length; i++) {
							y[i] = data[i];
						}
						// 收到历史饲喂量
						// 永久化数据

						x.updata(y, zhuti.split("&")[0]);

						Intent intent = new Intent("com.lcd.qyRec");// 参数过滤器筛选条件，可以理解为广播名称
						intent.putExtra("key2", "OK");
						sendBroadcast(intent);
					}
				} else if (b[0] == 0x64 && b[1] == 0x61 && b[2] == 0x74
						&& b[3] == 0x62) {
					x.updataNowLog(b,zhuti.split("&")[0]);//保存到数据库，并记录接收时间，并把未接收到数据标志清零

					// --------------------注册广播
					Intent intent = new Intent("com.lcd.qydangtianRec");// 参数过滤器筛选条件，可以理解为广播名称
					intent.putExtra("key2", "OK");
					sendBroadcast(intent);

				}

			}

			@Override
			public void onFileReceived(String arg0, DocumentInfo arg1) {
				// TODO 自动生成的方法存根

			}

			@Override
			public void onBroken(Server arg0, int arg1, String arg2) {
				// 已和服务器断开连接

			}
		});
	}

	/**
	 * 用户注册
	 *
	 * @param userName
	 *            用户名
	 */
	public void registUser(String userName) {
		SDKContextManager.registerUser(userName, "lb.kaifakuai.com", 8085,
				"33d8bcea-ae05-711133", "9ffcbc99885fb9c36c7d8512f5846488",
				new IFriendsActionListener() {

					@Override
					public void onSuccess() {
						// 该方法不会调用
					}

					@Override
					public void onFailure(final ErrorInfo e) {
						// 注册用户失败
						Log.i("test", "注册用户失败");
						Looper.prepare();
						Toast.makeText(MyApplication.getContext(), "注册用户失败", 2)
								.show();
						Looper.loop();
					}

					@Override
					public void onResultData(final Object arg0) {
						UserInfo userInfo = (UserInfo) arg0;
						// 注册用户成功
						new MyUser(SDKserver.this).updata(userInfo.getUserid());
						Register.getRegister().server.init();
						Register.getRegister().server.scanServer();
						Log.i("test", "注册用户成功");
						Intent intent = new Intent("com.lcd.qyzhuceRec");// 参数过滤器筛选条件，可以理解为广播名称
						intent.putExtra("key2", "OK");
						sendBroadcast(intent);
						Looper.prepare();
						Toast.makeText(MyApplication.getContext(), "注册用户成功", 2)
								.show();
						Looper.loop();
						// --------------------注册广播


					}
				});
	}

	// 扫描服务器
	public void scanServer() {
		sdkContext.discoverSvrs(10, new IActionListener() {

			@Override
			public void onSuccess() {
				// 正在扫描， 成功后在上面onServer中返回
				Log.e("scan", "正在扫描");
			}

			@Override
			public void onFailure(ErrorInfo arg0) {
				// 失败
				Log.e("scan", "扫描失败");
			}
		});
	}

	public void connectServer() {
		ConnectOptions cop = new ConnectOptions();
		cop.setConnectionTimeout(10);
		cop.setKeepAliveInterval((short) 60);
		cop.setCleanSession(true);// 不保存离线信息

		sdkContext.connect(server, cop, new IActionListener() {

			@Override
			public void onSuccess() {
				Log.e("connect", "连接成功");
				ArrayList<XiaoQunYnag> list = x.selectAll();
				for (int i = 0; i < list.size(); i++) {
					dingyue(list.get(i).getUid() + "&TX");
				}
				Looper.prepare();
				Toast.makeText(MyApplication.getContext(), "连接服务器成功", 2).show();
				Looper.loop();

			}

			@Override
			public void onFailure(ErrorInfo arg0) {
				Log.e("connect", "连接失败");

			}
		});
	}

	public void dingyue(String dingyue) {
		sdkContext.subscribe(dingyue, new IActionListener() {

			@Override
			public void onSuccess() {
				// 订阅成功
				Log.e("订阅", "成功");
			}

			@Override
			public void onFailure(ErrorInfo arg0) {
				// 订阅失败
				Log.e("订阅", "失败");
			}
		});
	}

	// 点对点发送
	public void send(byte mingling, String UID) {

		Message message = new Message();
		byte[] b = new byte[] { mingling };
		message.setPayload(b);

		sdkContext.chatTo(UID, message, new IActionListener() {

			@Override
			public void onSuccess() {
				// 已发送到服务器
				Log.e("Fc5wGsTuvumomVomLukWBenUcXDMHcj1h4", "发送到服务器");
			}

			@Override
			public void onFailure(ErrorInfo arg0) {
				// 发送失败
				Log.e("Fc5wGsTuvumomVomLukWBenUcXDMHcj1h4", "发送失败");
			}
		});

	}

	@Override
	public void onDestroy() {
		Log.e("server", "onDestroy");
		super.onDestroy();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.e("server", "onUnbind");
		return super.onUnbind(intent);
	}

}
